//
//  LoginVC.swift
//  kxf
//
//  Created by Mac on 2024/3/4.
//

import Foundation
import MCToast


class LoginVC : WHBaseViewVC{
    
    var getCodeTime = 60
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
    }
    lazy var topVm : LoginTopVM = {
        let vm = LoginTopVM.init(frame: .zero)
        
        return vm
    }()
    lazy var typeVm : LoginTypeVM = {
        let vm = LoginTypeVM.init(frame: CGRect.init(x: 0, y: self.topVm.frame.maxY+kFitWidth(10), width: 0, height: 0))
        vm.typeChangeBlock = {(type)in
            if type == "code"{
                self.codeLoginVm.isHidden = false
                self.pswLoginVm.isHidden = true
            }else{
                self.codeLoginVm.isHidden = true
                self.pswLoginVm.isHidden = false
            }
        }
        
        return vm
    }()
    lazy var codeLoginVm : CodeLoginVM = {
        let vm = CodeLoginVM.init(frame: CGRect.init(x: 0, y: self.typeVm.frame.maxY, width: 0, height: 0))
        vm.getCodeBlock = {()in
            self.getCodeRequest()
        }
        return vm
    }()
    lazy var pswLoginVm : PSWLoginVM = {
        let vm = PSWLoginVM.init(frame: CGRect.init(x: 0, y: self.typeVm.frame.maxY, width: 0, height: 0))
        vm.isHidden = true
        return vm
    }()
    lazy var loginVm : LoginButtonVM = {
        let vm = LoginButtonVM.init(frame: CGRect.init(x: 0, y: self.pswLoginVm.frame.maxY+kFitWidth(20), width: 0, height: 0))
        vm.registBlock = {()in
            let vc = RegisterVC()
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        }
        vm.forgetBlock = {()in
            let vc = UpdatePSWVC()
            vc.modalPresentationStyle = .fullScreen
            vc.isForget = true
            self.present(vc, animated: true)
        }
        vm.loginBlock = {()in
            if self.typeVm.loginType == "code"{
                self.sendLoginCodeRequest()
            }else{
                self.sendLoginPswRequest()
            }
        }
        
        return vm
    }()
    lazy var protocalVm : ProtocalVM = {
        let vm = ProtocalVM.init(frame: CGRect.init(x: 0, y: self.loginVm.frame.maxY, width: 0, height: 0))
        vm.controller = self
        return vm
    }()
}

extension LoginVC{
    func initUI() {
        view.addSubview(topVm)
        view.addSubview(typeVm)
        view.addSubview(codeLoginVm)
        view.addSubview(pswLoginVm)
        view.addSubview(loginVm)
        view.addSubview(protocalVm)
        
    }
    
    func changeRootVC() {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let newRootVC = LLTabBarViewController()
        appDelegate.switchRootViewController(to: newRootVC)
    }
}

extension LoginVC{
    func sendLoginPswRequest() {
        if !judgePhoneNumber(phoneNum: pswLoginVm.phoneVm.textField.text){
            MCToast.mc_text("请输入正确的手机号")
            return
        }
        if pswLoginVm.pswVm.textField.text?.count ?? 0 < 6{
            MCToast.mc_text("请输入六位数以上的密码")
            return
        }
        
        if protocalVm.isAgree == false{
            if UserModel.shared.isCheck == true{
                MCToast.mc_text("请阅读并同意《隐私政策》")
            }else{
                MCToast.mc_text("请阅读并同意《隐私政策》及《展业规范》")
            }
            
            return
        }
        MCToast.mc_loading()
        let param:[String:Any] = ["username":"\(pswLoginVm.phoneVm.textField.text ?? "")",
                                  "password":"\(pswLoginVm.pswVm.textField.text ?? "")"]
        WHNetworkUtil.shareManager().POST(urlString: URL_Login_phone, parameters: param  as [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            
            let dataObj = responseObject["data"] as? NSDictionary ?? [:]
            
//            if "\(dataObj["identity"] ?? "")" == "0"{
                UserDefaults.standard.setValue("\(dataObj["identity"] ?? "")", forKey: whIdentity)
                UserDefaults.standard.setValue("\(dataObj["tokenHead"] ?? "")", forKey: whTokenHead)
                UserDefaults.standard.setValue("\(dataObj["token"] ?? "")", forKey: whToken)
                UserDefaults.standard.setValue("\(dataObj["tokenHead"] ?? "")\(dataObj["token"] ?? "")", forKey: Authorization)
                
                self.changeRootVC()
//            }else{
//                self.presentAlertVcNoAction(title: "账户类型异常，请咨询代理商。", viewController: self)
//            }
        }
    }
    func sendLoginCodeRequest() {
        if !judgePhoneNumber(phoneNum: codeLoginVm.phoneVm.textField.text){
            MCToast.mc_text("请输入正确的手机号")
            return
        }
        if codeLoginVm.codeVm.textField.text?.count ?? 0 < 3{
            MCToast.mc_text("请输入正确的验证码")
            return
        }
        
        if protocalVm.isAgree == false{
            if UserModel.shared.isCheck == true{
                MCToast.mc_text("请阅读并同意《隐私政策》")
            }else{
                MCToast.mc_text("请阅读并同意《隐私政策》及《展业规范》")
            }
            return
        }
        MCToast.mc_loading()
        let param:[String:Any] = ["phone":"\(codeLoginVm.phoneVm.textField.text ?? "")",
                                  "verifyCode":"\(codeLoginVm.codeVm.textField.text ?? "")"]
        WHNetworkUtil.shareManager().POST(urlString: URL_Login_code, parameters: param  as [String : AnyObject],isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            
            let dataObj = responseObject["data"] as? NSDictionary ?? [:]
            
//            if "\(dataObj["identity"] ?? "")" == "0"{
                UserDefaults.standard.setValue("\(dataObj["identity"] ?? "")", forKey: whIdentity)
                UserDefaults.standard.setValue("\(dataObj["tokenHead"] ?? "")", forKey: whTokenHead)
                UserDefaults.standard.setValue("\(dataObj["token"] ?? "")", forKey: whToken)
                UserDefaults.standard.setValue("\(dataObj["tokenHead"] ?? "")\(dataObj["token"] ?? "")", forKey: Authorization)
                self.changeRootVC()
//            }else{
//                self.presentAlertVcNoAction(title: "账户类型异常，请咨询代理商。", viewController: self)
//            }
        }
    }
    @objc func getCodeRequest() {
        if !WHBaseViewVC().judgePhoneNumber(phoneNum: codeLoginVm.phoneVm.textField.text ?? ""){
            MCToast.mc_text("请输入正确的手机号")
            return
        }
        MCToast.mc_loading()
        self.codeLoginVm.codeVm.getCodeBtn.isUserInteractionEnabled = false
        let urlString = "\(URL_get_code)?phone=\(codeLoginVm.phoneVm.textField.text ?? "")&type=2"
        WHNetworkUtil.shareManager().GET(urlString: urlString,vc:self) { responseObject in
            DLLog(message: "getCodeRequest：\(responseObject)")
            
            MCToast.mc_text("验证码发送成功")
            let codeTimer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: .global())
            codeTimer.schedule(deadline: .now(), repeating: .milliseconds(1000))
            codeTimer.setEventHandler {
                self.getCodeTime = self.getCodeTime - 1
                
                if self.getCodeTime < 0{
                    codeTimer.cancel()
                    self.getCodeTime = 60
                    DispatchQueue.main.async {
                        self.codeLoginVm.codeVm.getCodeBtn.isUserInteractionEnabled = true
                        self.codeLoginVm.codeVm.getCodeBtn.setTitle("获取验证码", for: .normal)
                    }
                }else{
                    DispatchQueue.main.async {
                        self.codeLoginVm.codeVm.getCodeBtn.isUserInteractionEnabled = false
                        self.codeLoginVm.codeVm.getCodeBtn.setTitle("\(self.getCodeTime) 秒", for: .normal)
                    }
                }
            }
            if #available(iOS 10.0, *) {
                codeTimer.activate()
            } else {
                codeTimer.resume()
            }
        }
    }
}
